<template>
  <div>
    <el-row>
      <el-col :span="11" style="padding:12px;background:white;">
        <div class="the-list">
          <div class="panel-table">
            <div class="table-head">
            <span>
              亲密度对消息条数的限制
            </span>
              <div>
                <el-button type="primary" @click="mainFn.insertIntimacyConfig"
                           v-if="hasPermission(['intimacyConfig:insert'])">
                  添加
                </el-button>
              </div>
            </div>
          </div>
        </div>
        <el-table :data="tableData.list" stripe :header-cell-style="{backgroundColor:'#ededed',padding:'12px 0'}" border>
          <el-table-column label="亲密度" prop="dictLabel"/>
          <el-table-column label="单方面发送消息条数" prop="dictValue"/>

          <el-table-column fixed="right" label="操作" width="140px" align="center">
            <template #default="{row}">
              <el-button v-if="hasPermission(['intimacyConfig:update'])" size="small" type="primary" plain
                         @click="mainFn.updateIntimacyConfig(row)">
                修改
              </el-button>

              <el-button v-if="hasPermission(['intimacyConfig:del'])" size="small" type="danger" plain
                         @click="mainFn.deleteById(row.id)">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <div class="table-pagination" style="margin-top:12px;">
          <pagination :total="tableData.total" v-model:page="tableData.query.pageNum"
                      v-model:limit="tableData.query.pageSize" @pagination="tableFn.getTableList"/>
        </div>
      </el-col>

      <el-col :span="11" :offset="2" style="padding:12px;background:white;">

        <div class="the-list">
          <div class="panel-table">
            <div class="table-head">
            <span>
              亲密度增减规则
            </span>
            </div>
          </div>
        </div>

        <el-table :data="increaseDecreaseData.list" stripe
                  :header-cell-style="{backgroundColor:'#ededed',padding:'12px 0'}" border>
          <el-table-column label="触发事件" prop="dictLabel"/>
          <el-table-column label="亲密度变化">
            <template #default="{row}">

              <el-row>
                <el-col :span="10">
                  <el-select v-model="row.increaseDecrease" style="width:90%">
                    <el-option label="+" value="+"/>
                    <el-option label="-" value="-"/>
                  </el-select>
                </el-col>
                <el-col :span="14">
                  <el-input-number v-model="row.dictValue" :step="1" :min="0" :precision="0" :max="9999999"/>
                </el-col>
              </el-row>
            </template>
          </el-table-column>
        </el-table>

        <div class="sub_btn">
          <el-button class="package_manage_tabs_btn" type="primary" v-if="hasPermission(['packageManage:updatePetType'])"
                     @click="increaseDecreaseFn.updateIncreaseDecrease">
            确定
          </el-button>
        </div>
      </el-col>
    </el-row>

    <add-or-update :visible="mainData.visible" :edit-data="mainData.editData" @reload="tableFn.getTableList"
                   @close="mainFn.intimacyClose"/>
  </div>
</template>
<script>
import {reactive} from "vue";
import {ElMessage, ElMessageBox} from "element-plus";
import {getIntimacyConfig, delIntimacyConfig} from "../../../api/intimacyConfig";

import addOrUpdate from "./addOrUpdate.vue";
import {getBasicDataByCode, updateBasicDataByIdList} from "../../../api/basicData";

export default {
  name: "intimacyConfig",
  components: {addOrUpdate},
  setup(props) {
    const {$data: tableData, $fn: tableFn} = getTableData();
    const {$data: increaseDecreaseData, $fn: increaseDecreaseFn} = increaseDecrease();
    const {$data: mainData, $fn: mainFn} = intimacyConfigFun(tableFn);

    return {
      tableData, tableFn, mainData, mainFn, increaseDecreaseData, increaseDecreaseFn
    }
  },
}

function intimacyConfigFun(tableFn) {
  const $data = reactive({
    visible: false,
    editData: {},
  })
  const $fn = {
    updateIntimacyConfig(row) {
      $data.editData = row;
      $data.visible = true;
    },
    insertIntimacyConfig() {
      $data.editData = {}
      $data.visible = true;
    },
    intimacyClose() {
      $data.visible = false;
    },
    deleteById(id) {
      ElMessageBox.confirm("是否确认删除该套餐？", "确认删除", {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        $fn.deleteItem(id);
      }).catch(() => {
      });
    },
    deleteItem(id) {
      delIntimacyConfig({id: id}).then(row => {
        if (row.code === 0) {
          ElMessage.success("操作成功！");
        }
        tableFn.getTableList();
      }).catch(() => {
        ElMessage.error("操作失败");
        tableFn.getTableList();
      })
    },
  }

  return {$data, $fn}
}

function getTableData() {
  const backup = {
    query: {
      pageSize: 10,
      pageNum: 1,
    },
  };

  const $data = reactive({
    query: {...backup.query},
    list: [],
    total: 0,
  });
  const $fn = {
    getTableList() {
      getIntimacyConfig($data.query).then((res) => {
        if (res.code === 0) {
          $data.list = res.data.items;
          $data.total = res.data.pagination.total_record;
        }
      });
    },
    onResetQuery() {
      $data.query = {...backup.query};
      $fn.getTableList();
    },
    onSubmit() {
      $fn.getTableList();
    },
  };
  $fn.getTableList();
  return {$data, $fn,};
}

function increaseDecrease() {
  const $data = reactive({
    list: [],
  })
  const $fn = {
    getIncreaseDecrease() {
      getBasicDataByCode({code: "intimacy_increase_decrease"}).then((res) => {
        if (res.code === 0) {
          res.data.forEach(item => {
            if (item.dictValue) {
              let increase = item.dictValue.indexOf("+")
              let decrease = item.dictValue.indexOf("-")
              if (increase >= 0) {
                item.increaseDecrease = '+'
                item.dictValue = (item.dictValue.slice(1));
              } else if (decrease >= 0) {
                item.increaseDecrease = '-'
                item.dictValue = (item.dictValue.slice(1));
              }
            }
          })
          $data.list = res.data;
        }
      });
    },
    updateIncreaseDecrease() {
      let params = []
      $data.list.forEach(item => {
        if (item.dictValue && item.dictValue > 0 && item.increaseDecrease) {
          params.push(item)
        }
      })
      updateBasicDataByIdList(params).then(row => {
        if (row.code === 0) {
          ElMessage.success("操作成功！");
          $fn.getIncreaseDecrease();
        }
      }).catch(() => $fn.getIncreaseDecrease())
    },
  }
  $fn.getIncreaseDecrease();
  return {$data, $fn}
}

</script>
<style scoped>
/deep/ .sub_btn {
  margin-top: 16px;
  text-align: right;
}
</style>
<style scoped lang="scss">
@import "@/styles/tablePage.scss";
</style>


